import React, { useState, useContext } from "react";
import "./StudentForm.css";
import StuContext from '../store/StuContext';
import useFetch from '../hooks/useFetch';

function StudentForm(props) {
    const ctx = useContext(StuContext)
    
    const [inputdata, setInputdata] = useState({
        name:props.isEdit ? props.stu.name:'',
        gender:props.isEdit ? props.stu.gender:'男',
        age:props.isEdit ? props.stu.age:'',
        address:props.isEdit ? props.stu.address:''
    })
    //数据改变绑定
    const ChangeHandler = (e,type) => {
        setInputdata((prevState) => {
            //深拷贝一次 要不然返回prevState地址相同不会render
            const newInputdata = {...prevState}
            newInputdata[type] = e.target.value
            return newInputdata
        })

    }
    //添加,更新数据到数据库
    const {loading, error, fetchData:updataStu} = useFetch({
        url:props.isEdit ? `students/${props.stu.documentId}`:'students/',
        method:props.isEdit ? 'put' : 'post',
    },ctx.fetchData)
 
    
    const submitHandler = () => {
        updataStu(inputdata)
    }
    const stateText = props.isEdit?"修改":"添加";
    return (
        <>
        <tr className="student-form">
            {/* 姓名 */}
            <td>
                <input onChange={(e) => {ChangeHandler(e,"name")}}
                type="text"
                value={inputdata.name}
                />
            </td>
            {/* 性别 */}
            <td>
                <select
                    onChange={(e) => {ChangeHandler(e,"gender")}}
                    value={inputdata.gender}
                >
                    <option value="男">男</option>
                    <option value="女">女</option>
                </select>
            </td>
            {/* 年龄 */}
            <td>
                <input onChange={(e) => {ChangeHandler(e,"age")}}
                type="text"
                value={inputdata.age}
                />
            </td>
            {/* 地址 */}
            <td>
                <input onChange={(e) => {ChangeHandler(e,"address")}}
                type="text" 
                value={inputdata.address}
                />
            </td>
            <td>
                {props.isEdit?<button onClick={props.onCancel}>取消</button>:""}
                <button onClick={submitHandler}>{stateText}</button>
            </td>
        </tr>
        {loading && <tr><td colSpan={5}>正在{stateText}数据</td></tr>}
        {error && <tr><td colSpan={5}>{stateText}失败</td></tr>}
        </>
    );
}

export default StudentForm;
